<template>
  <div class="layout-container">
    <!-- 顶部导航栏 -->
    <el-header class="header">
      <div class="header-left">
        <h2>房屋租赁系统</h2>
      </div>
      <div class="header-right">
        <span>欢迎您，{{ username }}</span>
      </div>
    </el-header>

    <el-container class="main-container">
      <!-- 左侧导航栏 -->
      <el-aside width="250px" class="aside">
        <!-- 用户信息卡片 -->
        <div class="user-info">
          <el-avatar :size="64" :src="userAvatar">
            <img src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"/>
          </el-avatar>
          <h3>{{ username }}</h3>
          <el-button type="primary" size="small" @click="goToProfile">修改个人信息</el-button>
          <el-button type="danger" size="small" @click="handleLogout">退出登录</el-button>
        </div>

        <el-menu
          :default-active="currentMenuIndex"
          class="menu"
          background-color="#304156"
          text-color="#fff"
          active-text-color="#409EFF"
          @select="handleMenuSelect"
          :default-openeds="openedMenus"
        >
          <el-menu-item index="home">
            <el-icon><House /></el-icon>
            <span>首页</span>
          </el-menu-item>

          <el-sub-menu index="0">
            <template #title>
              <el-icon><Message /></el-icon>
              <span>消息中心</span>
            </template>
            <el-menu-item index="messages">消息列表</el-menu-item>
            <el-menu-item index="feedbacks">我的意见</el-menu-item>
          </el-sub-menu>
          <el-sub-menu index="1">
            <template #title>
              <el-icon><User /></el-icon>
              <span>我是租客</span>
            </template>
            <el-menu-item index="1-1">我的收藏</el-menu-item>
            <el-menu-item index="1-3">我的预约</el-menu-item>
            <el-menu-item index="1-4">我的订单</el-menu-item>
            <el-menu-item index="1-5">我的租房</el-menu-item>
          </el-sub-menu>

          <el-sub-menu index="2">
            <template #title>
              <el-icon><House /></el-icon>
              <span>我是房东</span>
            </template>
            <el-menu-item index="2-1" @click="showUploadDialog = true">我要出租</el-menu-item>
            <el-menu-item index="2-3" @click="gotoMyHouses">管理出租</el-menu-item>
            <el-menu-item index="2-4">预约反馈</el-menu-item>
            <el-menu-item index="2-5">维修反馈</el-menu-item>
            <el-menu-item index="2-6">租金收入</el-menu-item>
          </el-sub-menu>
        </el-menu>
      </el-aside>

      <!-- 主要内容区域 -->
      <el-main class="main">
        <!-- 根据activeTab显示不同内容 -->
        <div v-if="activeTab === 'welcome'">
          <el-row :gutter="20">
            <!-- 原有的欢迎页内容 -->
            <el-col :span="18">
              <el-card class="welcome-card">
                <template #header>
                  <div class="card-header">
                    <span>欢迎使用房屋租赁系统</span>
                  </div>
                </template>
                <div class="welcome-content">
                  <h3>尊敬的用户，欢迎您！</h3>
                  <p>这里是您的个人中心，您可以：</p>
                  <ul>
                    <li>浏览和收藏心仪的房源</li>
                    <li>管理您的租房预约和订单</li>
                    <li>发布和管理您的房源</li>
                    <li>查看租金收入和维修反馈</li>
                  </ul>
                </div>
              </el-card>
            </el-col>

            <!-- 右侧便捷服务 -->
            <el-col :span="6">
              <el-card class="ai-service-card">
                <template #header>
                  <div class="card-header">
                    <span>AI智能助手</span>
                  </div>
                </template>
                <div class="ai-service-content">
                  <el-button type="primary" @click="gotoai">AI职能助手</el-button>
                </div>
              </el-card>
              <div>
                <el-button type="primary" @click="continueBrowsing">浏览房屋信息</el-button>
                  <el-button type="primary" @click="showFeedbackDialog">提出意见</el-button>
              </div>
            </el-col>
          </el-row>
        </div>

        <div v-else-if="activeTab === 'myRentals'">
          <MyRental ref="myRentalRef" />
        </div>

        <div v-else-if="activeTab === 'myOrders'">
          <MyOrders ref="myOrdersRef" />
        </div>
        <!-- 消息列表内容 -->
        <div v-else-if="activeTab === 'messages'">
          <message-list v-if="activeTab === 'messages'" ref="messageListRef"/>
        </div>
        <!-- 在主要内容区域添加收藏列表 -->
        <div v-else-if="activeTab === 'collections'">
          <el-card class="collections-card">
            <template #header>
              <div class="card-header">
                <span>我的收藏</span>
              </div>
            </template>
            <el-empty v-if="collectedHouses.length === 0" description="暂无收藏"></el-empty>
            <div v-else class="house-list">
              <el-card
                v-for="house in collectedHouses"
                :key="house.house_id"
                class="house-item"
                shadow="hover"
              >
                <div class="house-info" @click="goToHouseDetail(house.house_id)">
                  <el-image
                    :src="formatImageUrl1(house.photo_url)"
                    fit="cover"
                    class="house-image"
                  ></el-image>
                  <div class="house-details">
                    <h3>{{ house.title }}</h3>
                    <p>{{ house.address }}</p>
                    <p class="price">¥{{ house.monthly_rent }}/月</p>
                  </div>
                </div>
                <div class="house-actions">
                  <el-button size="small" type="danger" @click.stop="cancelCollect(house.house_id)">取消收藏</el-button>
                </div>
              </el-card>
            </div>
          </el-card>
        </div>
        <!-- 我的预约 -->
        <div v-else-if="activeTab === 'appointments'">
            <el-card class="appointments-card">
              <template #header>
                <div class="card-header">我的预约</div>
              </template>
              <el-table :data="appointmentList" class="appointment-list">
                
                <!-- 房源信息 -->
                <el-table-column label="房源信息">
                  <template #default="scope">
                    {{ scope.row.house.description }}
                  </template>
                </el-table-column>

                <!-- 地址 -->
                <el-table-column label="地址">
                  <template #default="scope">
                    {{ scope.row.house.address }}
                  </template>
                </el-table-column>

                <!-- 预约时间 -->
                <el-table-column prop="appointment_time" label="预约时间" />

                <!-- 状态 -->
                <el-table-column prop="status" label="状态">
                  <template #default="scope">
                    <el-tag :type="getStatusType(scope.row.status)">
                      {{ getStatusText(scope.row.status) }}
                    </el-tag>
                  </template>
                </el-table-column>

                <!-- 操作 -->
                <el-table-column label="操作">
                  <template #default="scope">
                    <el-button
                      v-if="scope.row.status === 0"
                      type="danger"
                      size="small"
                      @click="cancelAppointment(scope.row.appointment_id)"
                    >取消预约</el-button>
                  </template>
                </el-table-column>

              </el-table>
            </el-card>
      </div>

          <!-- 预约处理（房东视角） -->
          <div v-else-if="activeTab === 'appointmentProcess'">
            <el-card class="appointments-card">
              <template #header><div class="card-header">预约处理</div></template>
              <el-table :data="landlordAppointmentList" class="appointment-process-list">
                <el-table-column label="房源信息">
                  <template #default="scope">
                    {{ scope.row.house.description }}
                  </template>
                </el-table-column>
                <el-table-column prop="client_name" label="预约人" />
                <el-table-column prop="appointment_time" label="预约时间" />
                <el-table-column prop="status" label="状态">
                  <template #default="scope">
                    <el-tag :type="getStatusType(scope.row.status)">
                      {{ getStatusText(scope.row.status) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作">
                  <template #default="scope">
                    <template v-if="scope.row.status === 0">
                      <el-button
                        type="success"
                        size="small"
                        @click="processAppointment(scope.row.appointment_id, 1)"
                      >接受</el-button>
                      <el-button
                        type="danger"
                        size="small"
                        @click="processAppointment(scope.row.appointment_id, 2)"
                      >拒绝</el-button>
                    </template>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </div>

          <!-- 添加租金收入页面 -->
          <div v-else-if="activeTab === 'income'">
            <el-card class="overview-card">
              <template #header>
                <div class="card-header">
                  <span>租金收入概览</span>
                  <el-button type="primary" size="small" @click="fetchIncomeOverview">刷新数据</el-button>
                </div>
              </template>

              <div class="overview-content" v-loading="overviewLoading">
                <el-row :gutter="20">
                  <el-col :span="12">
                    <div class="stat-item">
                      <div class="stat-title">总收入</div>
                      <div class="stat-value">¥ {{ formatCurrency(incomeOverview.total_income) }}</div>
                    </div>
                  </el-col>
                  <el-col :span="12">
                    <div class="stat-item">
                      <div class="stat-title">租赁订单数</div>
                      <div class="stat-value">{{ incomeOverview.total_rents }}</div>
                    </div>
                  </el-col>
                </el-row>
              </div>
            </el-card>

            <el-card class="details-card">
              <template #header>
                <div class="card-header">
                  <span>收入详情</span>
                  <el-button type="primary" size="small" @click="fetchIncomeDetails">刷新数据</el-button>
                </div>
              </template>

              <el-table
                :data="incomeDetails"
                style="width: 100%"
                border
                stripe
                v-loading="detailsLoading"
              >
                <el-table-column prop="house_id" label="房屋ID" width="80" />
                <el-table-column prop="house_address" label="房屋地址" min-width="200" show-overflow-tooltip />
                <el-table-column prop="monthly_rent" label="月租金" width="120">
                  <template #default="scope">
                    ¥ {{ formatCurrency(scope.row.monthly_rent) }}
                  </template>
                </el-table-column>
                <el-table-column prop="tenant_name" label="租户" width="120">
                  <template #default="scope">
                    {{ scope.row.tenant_name || '暂无租户' }}
                  </template>
                </el-table-column>
                <el-table-column prop="start_date" label="租期开始" width="120">
                  <template #default="scope">
                    {{ scope.row.start_date || '-' }}
                  </template>
                </el-table-column>
                <el-table-column prop="end_date" label="租期结束" width="120">
                  <template #default="scope">
                    {{ scope.row.end_date || '-' }}
                  </template>
                </el-table-column>
                <el-table-column prop="amount" label="租金总额" width="120">
                  <template #default="scope">
                    ¥ {{ formatCurrency(scope.row.amount) }}
                  </template>
                </el-table-column>
              </el-table>

              <div class="pagination-container">
                <el-pagination
                  :current-page="currentPage"
                  :page-size="pageSize"
                  :page-sizes="[10, 20, 50, 100]"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="total"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                />
              </div>
            </el-card>
          </div>

          <!-- 添加维修反馈页面 -->
          <div v-else-if="activeTab === 'maintenance'">
            <el-card class="main-card">
              <template #header>
                <div class="card-header">
                  <span>维修反馈管理</span>
                  <el-button type="primary" size="small" @click="fetchMaintenanceRequests">刷新数据</el-button>
                </div>
              </template>

              <!-- 筛选 -->
              <div class="search-container">
                <el-select v-model="statusFilter" placeholder="处理状态" clearable>
                  <el-option label="全部" value="" />
                  <el-option label="待处理" value="待处理" />
                  <el-option label="处理中" value="处理中" />
                  <el-option label="已完成" value="已完成" />
                  <el-option label="已取消" value="已取消" />
                </el-select>
                <el-button type="primary" @click="searchMaintenanceRequests">搜索</el-button>
              </div>

              <!-- 表格 -->
              <el-table
                :data="maintenanceList"
                border
                stripe
                style="width: 100%"
                v-loading="loading"
              >
                <el-table-column prop="request_id" label="请求ID" width="80" />
                <el-table-column prop="tenant_name" label="租户姓名" width="120" />
                <el-table-column prop="house_address" label="房屋地址" min-width="150" show-overflow-tooltip />
                <el-table-column prop="content" label="维修内容" min-width="200" show-overflow-tooltip />
                <el-table-column prop="submitted_at" label="提交时间" width="180" />
                <el-table-column prop="status" label="状态" width="100">
                  <template #default="scope">
                    <el-tag :type="getStatusTag(scope.row.status)">
                      {{ scope.row.status }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="200" fixed="right">
                  <template #default="scope">
                    <el-button size="small" @click="viewMaintenanceDetails(scope.row)">查看</el-button>
                    <el-button v-if="scope.row.status === '待处理'" size="small" type="primary" @click="startProcessing(scope.row)">开始处理</el-button>
                    <el-button v-if="scope.row.status === '处理中'" size="small" type="success" @click="completeProcessing(scope.row)">完成处理</el-button>
                  </template>
                </el-table-column>
              </el-table>

              <!-- 分页 -->
              <div class="pagination-container">
                <el-pagination
                  :current-page="currentPage1"
                  :page-size="pageSize1"
                  :page-sizes="[10, 20, 50, 100]"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="total1"
                  @size-change="handleSizeChange1"
                  @current-change="handleCurrentChange1"
                />
              </div>
            </el-card>

            <!-- 维修详情弹窗 -->
            <el-dialog
              v-model="maintenanceDetailVisible"
              title="维修详情"
              width="600px"
            >
              <div v-if="currentMaintenance" class="maintenance-detail">
                <el-descriptions :column="1" border>
                  <el-descriptions-item label="请求ID">{{ currentMaintenance.request_id }}</el-descriptions-item>
                  <el-descriptions-item label="租户姓名">{{ currentMaintenance.tenant_name }}</el-descriptions-item>
                  <el-descriptions-item label="房屋地址">{{ currentMaintenance.house_address }}</el-descriptions-item>
                  <el-descriptions-item label="维修内容">{{ currentMaintenance.content }}</el-descriptions-item>
                  <el-descriptions-item label="提交时间">{{ formatDateTime(currentMaintenance.submitted_at) }}</el-descriptions-item>
                  <el-descriptions-item label="状态">
                    <el-tag :type="getStatusTag(currentMaintenance.status)">
                      {{ currentMaintenance.status }}
                    </el-tag>
                  </el-descriptions-item>
                  <el-descriptions-item v-if="currentMaintenance.processed_at" label="处理时间">
                    {{ formatDateTime(currentMaintenance.processed_at) }}
                  </el-descriptions-item>
                  <el-descriptions-item v-if="currentMaintenance.result_notes" label="处理结果">
                    {{ currentMaintenance.result_notes }}
                  </el-descriptions-item>
                </el-descriptions>

                <div v-if="currentMaintenance.status === '处理中'" class="result-form">
                  <h4>处理结果</h4>
                  <el-form>
                    <el-form-item>
                      <el-input
                        v-model="resultNotes"
                        type="textarea"
                        :rows="4"
                        placeholder="请输入处理结果"
                      />
                    </el-form-item>
                    <el-form-item>
                      <el-button type="success" @click="completeProcessing(currentMaintenance)">完成处理</el-button>
                    </el-form-item>
                  </el-form>
                </div>
              </div>
            </el-dialog>
          </div>


          <!-- 添加意见列表页面 -->
          <div v-else-if="activeTab === 'feedbacks'">
              <el-card class="feedback-card">
                <template #header>
                  <div class="card-header">我的意见</div>
                </template>
                <el-table
                  :data="feedbackList"
                  class="feedback-list"
                  border
                  empty-text="暂无反馈记录"
                >
                  <el-table-column prop="content" label="意见内容" />
                  
                  <el-table-column prop="submitted_at" label="提交时间">
                    <template #default="scope">
                      {{ formatTime(scope.row.submitted_at) }}
                    </template>
                  </el-table-column>

                  <el-table-column prop="status" label="状态">
                    <template #default="scope">
                      <el-tag :type="scope.row.status === '未处理' ? 'warning' : 'success'">
                        {{ scope.row.status }}
                      </el-tag>
                    </template>
                  </el-table-column>

                  <el-table-column prop="reply" label="管理员回复">
                    <template #default="scope">
                      {{ scope.row.reply || '暂无回复' }}
                    </template>
                  </el-table-column>

                  <el-table-column prop="processed_at" label="回复时间">
                    <template #default="scope">
                      {{ scope.row.processed_at ? formatTime(scope.row.processed_at) : '——' }}
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </div>


      </el-main>
    </el-container>
    

    <!-- 个人信息修改弹窗 -->
    <el-dialog
      v-model="showProfileDialog"
      title="修改个人信息"
      width="500px"
      @close="handleClose"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <!-- 当前密码验证 -->
        <el-form-item label="当前密码" prop="old_password">
          <el-input v-model="form.old_password" type="password" show-password></el-input>
        </el-form-item>

        <!-- 选择要修改的信息类型 -->
        <el-form-item label="修改项目">
          <el-select v-model="editType" placeholder="请选择要修改的信息">
            <el-option label="账户名" value="account_name"></el-option>
            <el-option label="账号" value="username"></el-option>
            <el-option label="密码" value="password"></el-option>
          </el-select>
        </el-form-item>

        <!-- 根据选择显示对应的输入框 -->
        <template v-if="editType === 'username'">
          <el-form-item label="新账号" prop="username">
            <el-input v-model="form.username"></el-input>
          </el-form-item>
        </template>

        <template v-if="editType === 'account_name'">
          <el-form-item label="新账户名" prop="account_name">
            <el-input v-model="form.account_name"></el-input>
          </el-form-item>
        </template>

        <template v-if="editType === 'password'">
          <el-form-item label="新密码" prop="password">
            <el-input v-model="form.password" type="password" show-password></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="confirm_password">
            <el-input v-model="form.confirm_password" type="password" show-password></el-input>
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 房源上传弹窗 -->
    <el-dialog
      v-model="showUploadDialog"
      title="发布房源信息"
      width="65%"
      @close="handleUploadClose"
    >
      <el-form
        ref="houseFormRef"
        :model="houseForm"
        :rules="houseRules"
        label-width="120px"
        class="house-form"
      >
        <!-- 图片上传 -->
        <el-form-item label="房源图片" prop="photo">
        <el-upload
          class="house-photo-uploader"
          action="http://127.0.0.1:5000/api/landlord/house"
          method="post"
          :auto-upload="false"
          :on-change="handlePhotoChange"
          :on-remove="handleRemovePhoto"
          :limit="1"
          accept=".jpg,.jpeg,.png,.gif"
          list-type="picture-card"
          :file-list="photoList"
        >
          <template #default>
            <el-icon class="upload-icon"><Plus /></el-icon>
            <div class="upload-text">点击上传图片</div>
          </template>
        </el-upload>
      </el-form-item>

        <!-- 基本信息 -->
        <el-form-item label="月租金" prop="monthly_rent">
          <el-input-number
            v-model="houseForm.monthly_rent"
            :min="0"
            :precision="2"
            :step="100"
          >
            <template #append>元/月</template>
          </el-input-number>
        </el-form-item>

        <el-form-item label="出租方式" prop="rental_method">
          <el-radio-group v-model="houseForm.rental_method">
            <el-radio label="整租">整租</el-radio>
            <el-radio label="合租">合租</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="房屋户型" prop="house_type">
          <el-input v-model="houseForm.house_type" placeholder="例如：2室1厅1卫" />
        </el-form-item>

        <el-form-item label="建筑面积" prop="floor_area">
          <el-input-number
            v-model="houseForm.floor_area"
            :min="0"
            :precision="2"
            :step="1"
          >
            <template #append>平方米</template>
          </el-input-number>
        </el-form-item>

        <el-form-item label="房屋朝向" prop="orientation">
          <el-select v-model="houseForm.orientation" placeholder="请选择房屋朝向">
            <el-option label="东" value="东" />
            <el-option label="南" value="南" />
            <el-option label="西" value="西" />
            <el-option label="北" value="北" />
            <el-option label="东南" value="东南" />
            <el-option label="东北" value="东北" />
            <el-option label="西南" value="西南" />
            <el-option label="西北" value="西北" />
          </el-select>
        </el-form-item>

        <el-form-item label="装修程度" prop="decoration">
          <el-select v-model="houseForm.decoration" placeholder="请选择装修程度">
            <el-option label="毛坯" value="毛坯" />
            <el-option label="简装" value="简装" />
            <el-option label="精装" value="精装" />
          </el-select>
        </el-form-item>

        <el-form-item label="所在区域" prop="district">
          <el-input v-model="houseForm.district" placeholder="请输入所在区域" />
        </el-form-item>

        <el-form-item label="详细地址" prop="address">
          <el-input
            v-model="houseForm.address"
            type="textarea"
            placeholder="请输入详细地址"
          />
        </el-form-item>

        <el-form-item label="房源描述" prop="description">
          <el-input
            v-model="houseForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入房源描述信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleUploadClose">取消</el-button>
          <el-button type="primary" @click="submitHouseForm(houseFormRef)">发布房源</el-button>
        </span>
      </template>
    </el-dialog>

  <!-- 添加意见反馈弹窗 -->
    <el-dialog
      v-model="feedbackDialogVisible"
      title="提出意见"
      width="500px"
      center
    >
      <el-form :model="feedbackForm" label-position="top">
        <el-form-item label="意见内容" prop="content">
          <el-input
            v-model="feedbackForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入您的意见或建议"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="feedbackDialogVisible = false">取消（Esc）</el-button>
          <el-button type="primary" @click="submitFeedback">提交(Q)</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加手机验证组件 -->
    <PhoneVerification
      v-model:visible="showPhoneVerification"
      @verified="handlePhoneVerified"
    />

  </div>
  
</template>

<script setup>
import dayjs from 'dayjs'
import { ref, reactive, onMounted, onBeforeUnmount, watch } from 'vue'
import { User, House, Plus, Delete } from '@element-plus/icons-vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import axios from 'axios'
import request from '../utils/request'  // 导入封装好的 axios 实例
import MessageList from '../views/MessageList.vue'
import MyRental from '../views/MyRental.vue'
import MyOrders from '../views/MyOrders.vue'
import PhoneVerification from '../components/PhoneVerification.vue'

const router = useRouter()
const route = useRoute()
const username = ref('')
const aiAdvice = ref('')
const userAvatar = ref('')
const showProfileDialog = ref(false)
const showUploadDialog = ref(false)
const editType = ref('')
const formRef = ref(null)
const feedbackDialogVisible = ref(false)
const feedbackForm = ref({ content: '' })
const feedbackList = ref([])
const messageListRef = ref(null)
const myRentalRef = ref(null)

// 当前激活的标签页
const activeTab = ref('welcome')

// 导航菜单状态
const currentMenuIndex = ref('home')
const openedMenus = ref([])

// 映射activeTab到菜单索引
const getMenuIndexFromTab = (tab) => {
  const tabToMenuMap = {
    'welcome': 'home',
    'messages': 'messages',
    'feedbacks': 'feedbacks',
    'collections': '1-1',
    'appointments': '1-3',
    'myOrders': '1-4',
    'myRentals': '1-5',
    'appointmentProcess': '2-4',
    'maintenance': '2-5',
    'income': '2-6'
  }
  return tabToMenuMap[tab] || 'home'
}

// 获取父菜单索引
const getParentMenuIndex = (index) => {
  if (index === 'messages' || index === 'feedbacks') {
    return '0'
  } else if (index.startsWith('1-')) {
    return '1'
  } else if (index.startsWith('2-')) {
    return '2'
  }
  return null
}

let refreshTimer = null

// 租金收入部分
const overviewLoading = ref(false)
const detailsLoading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const incomeOverview = ref({
  total_income: 0,
  total_rents: 0
})
const incomeDetails = ref([])

// 格式化货币
const formatCurrency = (value) => {
    if (!value && value !== 0) return '-'
    return value.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
  }
  
  // 获取收入概览
  const fetchIncomeOverview = async () => {
    overviewLoading.value = true
    try {
      console.log('获取收入概览...')
      const response = await request.get('/landlord/income/overview')
      console.log('获取收入概览响应:', response)
      
      if (response && response.status === 200 && response.data) {
        incomeOverview.value = {
          total_income: response.data.total_income,
          total_rents: response.data.total_rents
        }
      } else {
        ElMessage.error(response.msg || '获取收入概览失败')
      }
    } catch (error) {
      console.error('获取收入概览失败:', error)
      ElMessage.error('获取收入概览失败，请稍后重试')
    } finally {
      overviewLoading.value = false
    }
  }
  
  // 获取收入详情
  const fetchIncomeDetails = async () => {
    detailsLoading.value = true
    try {
      console.log('获取收入详情...')
      const response = await request.get('/landlord/income/details', {
        params: {
          page: currentPage.value,
          per_page: pageSize.value
        }
      })
      console.log('获取收入详情响应:', response)
      
      if (response && response.status === 200 && response.data) {
        incomeDetails.value = response.data.income_details
        total.value = response.data.total
      } else {
        ElMessage.error(response.msg || '获取收入详情失败')
      }
    } catch (error) {
      console.error('获取收入详情失败:', error)
      ElMessage.error('获取收入详情失败，请稍后重试')
    } finally {
      detailsLoading.value = false
    }
  }
  
  // 处理页码变化
  const handleCurrentChange = (val) => {
    currentPage.value = val
    fetchIncomeDetails()
  }
  
  // 处理每页显示数量变化
  const handleSizeChange = (val) => {
    pageSize.value = val
    currentPage.value = 1
    fetchIncomeDetails()
  }

// 维修列表部分
const statusFilter = ref('')
const maintenanceList = ref([])
const loading = ref(false)
const currentPage1 = ref(1)
const pageSize1 = ref(10)
const total1 = ref(0)
const maintenanceDetailVisible = ref(false)
const currentMaintenance = ref(null)
const resultNotes = ref('')
// 获取状态标签样式
const getStatusTag = (status) => {
  const statusMap = {
    '待处理': 'danger',
    '处理中': 'warning',
    '已完成': 'success',
    '已取消': 'info'
  }
  return statusMap[status] || 'info'
}

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return '-'
  return dayjs(timeStr).format('YYYY-MM-DD HH:mm:ss')
}

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return ''
  const date = new Date(dateTimeStr)
  return date.toLocaleString()
}

// 获取维修请求列表
const fetchMaintenanceRequests = async () => {
  loading.value = true
  try {
    console.log('获取维修请求列表...')
    const response = await request.get('/landlord/maintenance', {
      params: {
        page: currentPage1.value,
        per_page: pageSize1.value,
        status: statusFilter.value
      }
    })
    console.log('获取维修请求列表响应:', response)
    
    if (response && response.status === 200 && response.data) {
      maintenanceList.value = response.data.maintenance_requests
      total1.value = response.data.total
    } else {
      ElMessage.error(response.msg || '获取维修请求列表失败')
    }
  } catch (error) {
    console.error('获取维修请求列表失败:', error)
    ElMessage.error('获取维修请求列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 搜索维修请求
const searchMaintenanceRequests = () => {
  currentPage1.value = 1
  fetchMaintenanceRequests()
}

// 查看维修详情
const viewMaintenanceDetails = (maintenance) => {
  currentMaintenance.value = maintenance
  resultNotes.value = maintenance.result_notes || ''
  maintenanceDetailVisible.value = true
}

// 开始处理维修请求
const startProcessing = (maintenance) => {
  ElMessageBox.confirm(
    '确定要开始处理该维修请求吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      console.log('开始处理维修请求...')
      const response = await request.put(`/landlord/maintenance/${maintenance.request_id}`, {
        status: '处理中'
      })
      console.log('开始处理维修请求响应:', response)
      
      if (response && response.status === 200) {
        ElMessage.success('已开始处理维修请求')
        // 刷新列表
        await fetchMaintenanceRequests()
      } else {
        ElMessage.error(response.msg || '操作失败')
      }
    } catch (error) {
      console.error('开始处理维修请求失败:', error)
      ElMessage.error('操作失败：' + error.message)
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 完成处理维修请求
const completeProcessing = (maintenance) => {
  ElMessageBox.confirm(
    '确定要完成该维修请求的处理吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      console.log('完成处理维修请求...')
      const response = await request.put(`/landlord/maintenance/${maintenance.request_id}`, {
        status: '已完成',
        result_notes: resultNotes.value
      })
      console.log('完成处理维修请求响应:', response)
      
      if (response && response.status === 200) {
        ElMessage.success('维修请求已完成处理')
        // 关闭详情弹窗
        maintenanceDetailVisible.value = false
        // 刷新列表
        await fetchMaintenanceRequests()
      } else {
        ElMessage.error(response.msg || '操作失败')
      }
    } catch (error) {
      console.error('完成处理维修请求失败:', error)
      ElMessage.error('操作失败：' + error.message)
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 处理维修请求列表页码变化
const handleCurrentChange1 = (val) => {
  currentPage1.value = val
  fetchMaintenanceRequests()
}

// 处理维修请求列表每页显示数量变化
const handleSizeChange1 = (val) => {
  pageSize1.value = val
  currentPage1.value = 1
  fetchMaintenanceRequests()
}


const photoList = ref([])
const gotoMyHouses = () => {
  router.push({
    path: '/my-houses',
    query: { returnTo: 'welcome' }
  })
}
// 房源表单相关
const houseFormRef = ref(null)

const houseForm = reactive({
  photo: '',
  monthly_rent: 0,
  rental_method: '整租',
  house_type: '',
  floor_area: 0,
  orientation: '',
  decoration: '',
  district: '',
  address: '',
  description: ''
})

const houseRules = {
  monthly_rent: [{ required: true, message: '请输入月租金', trigger: 'blur' }],
  rental_method: [{ required: true, message: '请选择出租方式', trigger: 'change' }],
  house_type: [{ required: true, message: '请输入房屋户型', trigger: 'blur' }],
  floor_area: [{ required: true, message: '请输入建筑面积', trigger: 'blur' }],
  orientation: [{ required: true, message: '请选择房屋朝向', trigger: 'change' }],
  decoration: [{ required: true, message: '请选择装修程度', trigger: 'change' }],
  district: [{ required: true, message: '请输入所在区域', trigger: 'blur' }],
  address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }]
}

// 个人信息表单
const form = ref({
  old_password: '',
  username: '',
  account_name: '',
  password: '',
  confirm_password: ''
})

// 全局键盘事件处理函数
const handleFeedbackKeydown = (e) => {
  // 处理Ctrl+Q快捷键
  if (e.ctrlKey && e.key === 'q') {
    e.preventDefault() // 阻止默认行为
    if (feedbackDialogVisible.value) {
      submitFeedback()
    }
  }
}

// 显示意见反馈弹窗
function showFeedbackDialog() {
  feedbackDialogVisible.value = true
  feedbackForm.value.content = ''
  
  // 添加键盘事件监听
  window.addEventListener('keydown', handleFeedbackKeydown)
}

// 提交意见
async function submitFeedback() {
  if (!feedbackForm.value.content.trim()) {
    ElMessage.warning('请输入意见内容')
    return
  }
  try {
    await request.post('/consultation/create', {
      user_id: localStorage.getItem('userId'),
      content: feedbackForm.value.content
    })
    ElMessage.success('意见提交成功')
    feedbackDialogVisible.value = false
    
    // 移除键盘事件监听
    window.removeEventListener('keydown', handleFeedbackKeydown)
    
    if (activeTab === 'feedbacks') {
      getFeedbackList()
    }
  } catch (error) {
    ElMessage.error('提交失败：' + error.message)
  }
}

// 获取意见列表
async function getFeedbackList() {
  try {
    console.log('获取意见列表...')
    const response = await request.get(`/consultation/user/${localStorage.getItem('userId')}`)
    console.log('获取意见列表响应:', response)
    
    // 根据后端返回的数据结构调整访问方式
    if (response && response.data) {
      feedbackList.value = response.data
    } else {
      feedbackList.value = []
    }
  } catch (error) {
    console.error('获取意见列表失败:', error)
    ElMessage.error('获取意见列表失败：' + error.message)
  }
}
const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== form.value.password) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const rules = {
  old_password: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请输入新用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  account_name: [
    { required: true, message: '请输入新账户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirm_password: [
    { required: true, validator: validatePass, trigger: 'blur' }
  ]
}

onMounted(() => {
  username.value = localStorage.getItem('username') || '用户'
  userAvatar.value = localStorage.getItem('userAvatar') || ''
  
  // 设置默认标签为欢迎页
  activeTab.value = 'welcome'
  
  // 检查路由参数中是否有activeTab
  if (route.query.activeTab) {
    activeTab.value = route.query.activeTab
    
    // 设置当前选中的菜单项
    const menuIndex = getMenuIndexFromTab(activeTab.value)
    currentMenuIndex.value = menuIndex
    
    // 设置需要展开的菜单
    const parentIndex = getParentMenuIndex(menuIndex)
    if (parentIndex) {
      openedMenus.value = [parentIndex]
    }
    
    // 如果是消息列表，立即刷新一次
    if (activeTab.value === 'messages') {
      setTimeout(() => {
        messageListRef.value?.fetchConversations()
      }, 500)
    } else if (activeTab.value === 'collections') {
      // 如果是收藏列表，立即获取数据
      fetchCollectedHouses()
    }
  } else {
    // 如果没有路由参数，设置默认菜单为home
    currentMenuIndex.value = 'home'
  }
  
  // 检查用户手机验证状态
  checkPhoneVerification()
})

// 检查手机验证状态
const checkPhoneVerification = async () => {
  try {
    console.log('开始检查手机验证状态...')
    const response = await request.get('/users/check-phone-verified')
    console.log('检查手机验证状态响应:', response)
    
    // 如果手机未验证，显示验证对话框
    if (response && response.status === 200 && response.data && !response.data.phone_verified) {
      console.log('手机未验证，显示验证对话框')
      showPhoneVerification.value = true
    }
  } catch (error) {
    console.error('检查手机验证状态失败:', error)
  }
}

// 处理手机验证成功
const handlePhoneVerified = (phone) => {
  ElMessage.success(`手机号 ${phone} 验证成功`)
  showPhoneVerification.value = false
}

onBeforeUnmount(() => {
  // 清理可能存在的 blob URL
  if (houseForm.photo && houseForm.photo.startsWith('blob:')) {
    URL.revokeObjectURL(houseForm.photo)
  }
})

const handlePhotoChange = (file, fileList) => {
  photoList.value = fileList.slice(-1) // 只保留最新一张
}
const handleRemovePhoto = (file, fileList) => {
  photoList.value = fileList
}

const handleUploadClose = () => {
  showUploadDialog.value = false
  resetHouseForm(houseFormRef.value)
}

const submitHouseForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        const formData = new FormData()
        // 只上传一张图片
        if (photoList.value.length > 0 && photoList.value[0].raw) {
          formData.append('photo', photoList.value[0].raw)
        }
        Object.keys(houseForm).forEach(key => {
          if (key !== 'photo') {
            formData.append(key, houseForm[key])
          }
        })
        const response = await request.post('/landlord/house', formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          }
        })
        if (response && response.status === 200) {
          ElMessage.success('房源发布成功')
          resetHouseForm(formEl)
          showUploadDialog.value = false
        } else {
          ElMessage.error(response.msg || '发布失败')
        }
      } catch (error) {
        console.error('发布房源失败:', error)
        ElMessage.error('发布失败，请稍后重试')
      }
    }
  })
}

const resetHouseForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
  photoList.value = []
  houseForm.photo = ''
}

// 个人信息相关方法
const goToProfile = () => {
  showProfileDialog.value = true
  editType.value = ''
  form.value = {
    old_password: '',
    username: '',
    account_name: '',
    password: '',
    confirm_password: ''
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const data = {
          old_password: form.value.old_password
        }
        
        if (editType.value === 'username') {
          data.username = form.value.username
        } else if (editType.value === 'account_name') {
          data.account_name = form.value.account_name
        } else if (editType.value === 'password') {
          data.password = form.value.password
        }

        const response = await request.post('/users/updateUserInfo', data, {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`
          },
          params: { user_id: localStorage.getItem('userId') }
        })

        if (response && response.status === 200) {
          ElMessage.success(response.msg)
          if (editType.value === 'username') {
            localStorage.setItem('username', form.value.username)
            username.value = form.value.username
          } else if (editType.value === 'account_name') {
            localStorage.setItem('account_name', form.value.account_name)
            localStorage.setItem('username', form.value.account_name)
            username.value = form.value.account_name
          }
          handleClose()
        } else {
          ElMessage.error(response.msg || '修改失败')
        }
      } catch (error) {
        console.error('修改失败:', error)
        ElMessage.error(error.response?.data?.msg || '修改失败，请稍后重试')
      }
    }
  })
}

const handleClose = () => {
  showProfileDialog.value = false
  resetForm(formRef.value)
}

const resetForm = (formEl) => {
  if (formEl) {
    formEl.resetFields()
  }
}

const gotoai = () => {
  router.push('/aichat')
}

const handleLogout = () => {
  ElMessageBox.confirm(
    '确定要退出登录吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    localStorage.removeItem('token')
    localStorage.removeItem('userId')
    localStorage.removeItem('isAdmin')
    localStorage.removeItem('username')
    localStorage.removeItem('userAvatar')
    
    ElMessage.success('已成功退出登录')
    router.push('/login')
  }).catch(() => {})
}

const continueBrowsing = () => {
  router.push('/house')
}

// 收藏列表数据
const collectedHouses = ref([])

// 获取收藏列表
async function fetchCollectedHouses() {
  try {
    console.log('获取收藏列表...')
    const response = await request.get('/collect/list', {
      params: { user_id: localStorage.getItem('userId') }
    })
    console.log('获取收藏列表响应:', response)
    
    if (response && response.status === 200 && response.data) {
      collectedHouses.value = response.data
    }
  } catch (error) {
    console.error('获取收藏列表失败:', error)
    ElMessage.error('获取收藏列表失败')
  }
}

// 取消收藏
async function cancelCollect(houseId) {
  try {
    const response = await request.post('/collect/cancel', {
      user_id: localStorage.getItem('userId'),
      house_id: houseId
    })
    
    if (response && response.status === 200) {
      ElMessage.success('取消收藏成功')
      await fetchCollectedHouses()
    }
  } catch (error) {
    console.error('取消收藏失败:', error)
    ElMessage.error('取消收藏失败')
  }
}

// 点击房屋跳转到详情页
function goToHouseDetail(houseId) {
  router.push(`/house/${houseId}`)
}

// 修改菜单选择处理函数
const handleMenuSelect = (index) => {
  if (index === '1-1') {
    activeTab.value = 'collections'
    fetchCollectedHouses()
  }
  switch (index) {
    case 'home':
      activeTab.value = 'welcome'  // 切回首页标签
      break
    case 'messages':
      activeTab.value = 'messages'
      break
    case 'feedbacks':
      activeTab.value = 'feedbacks'
      getFeedbackList()
      break
    case '1-3':
      activeTab.value = 'appointments'
      fetchAppointments()
      break
    case '1-4': // 我的订单
      activeTab.value = 'myOrders'
      break
    case '1-5': // 我的租房
      activeTab.value = 'myRentals'
      break
    case '2-4':
      activeTab.value = 'appointmentProcess'
      fetchLandlordAppointments()
      break
    case '1-1': // 租客收藏列表
      activeTab.value = 'collections'
      break
    case '1-2': // 租客消息列表
      activeTab.value = 'tenant-messages'
      break
    case '2-2': // 房东消息列表
      activeTab.value = 'landlord-messages'
      break
    case '2-5': // 维修反馈
      //router.push('/landlord/maintenance');
      activeTab.value = 'maintenance'
      fetchMaintenanceRequests()
      break;
    case '2-6': // 租金收入
      //router.push('/landlord/income');
      activeTab.value = 'income'
      fetchIncomeOverview()
      fetchIncomeDetails()
      break;
    default:
      activeTab.value = 'welcome'
  }
}
const formatImageUrl1 = (url) => {
  if (!url) return 'https://via.placeholder.com/800x600?text=暂无图片'
  if (url.includes('house-img')) {
    const filename = url.split(/[/\\]/).pop()
    return `http://127.0.0.1:5000/static/house-img/${filename}`
  }
  return url
}
// 预约状态相关
const getStatusType = (status) => {
  const types = {
    0: 'info',
    1: 'success',
    2: 'danger',
    3: 'warning'
  }
  return types[status] || 'info'
}

// 获取预约列表（租客视角）
const appointmentList = ref([])
const fetchAppointments = async () => {
  try {
    console.log('获取预约列表...')
    const response = await request.get(`/appointment/client/${localStorage.getItem('userId')}`)
    console.log('获取预约列表响应:', response)
    
    if (response && response.code === 200 && response.data) {
      appointmentList.value = response.data.map(item => ({
        ...item,
        house: item.house,
        statusText: getStatusText(item.status)
      }))
    }
  } catch (error) {
    console.error('获取预约列表失败:', error)
    ElMessage.error('获取预约列表失败：' + error.message)
  }
}

// 获取预约列表（房东视角）
const landlordAppointmentList = ref([])
const fetchLandlordAppointments = async (status) => {
  try {
    console.log('获取房东预约列表...')
    const url = `/appointment/landlord/${localStorage.getItem('userId')}`
    const params = status !== undefined ? { status } : {}
    const response = await request.get(url, { params })
    console.log('获取房东预约列表响应:', response)
    
    if (response && response.code === 200 && response.data) {
      landlordAppointmentList.value = response.data.map(item => ({
        ...item,
        house: item.house,
        client_name: item.client_name,
        statusText: getStatusText(item.status)
      }))
    }
  } catch (error) {
    console.error('获取房东预约列表失败:', error)
    ElMessage.error('获取预约列表失败：' + error.message)
  }
}

// 取消预约
const cancelAppointment = async (appointmentId) => {
  try {
    const response = await request.put(`/appointment/cancel/${appointmentId}`)
    if (response && response.code === 200) {
      ElMessage.success('取消预约成功')
      await fetchAppointments() // 刷新列表
    }
  } catch (error) {
    console.error('取消预约失败:', error)
    ElMessage.error('取消预约失败：' + error.message)
  }
}

// 处理预约（接受/拒绝）
const processAppointment = async (appointmentId, status) => {
  try {
    const response = await request.put('/appointment/process', {
      appointment_id: appointmentId,
      status: status // 1: 接受, 2: 拒绝
    })
    if (response && response.code === 200) {
      ElMessage.success(status === 1 ? '已接受预约' : '已拒绝预约')
      await fetchLandlordAppointments() // 刷新列表
    }
  } catch (error) {
    console.error('处理预约失败:', error)
    ElMessage.error('操作失败：' + error.message)
  }
}

// 获取预约状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '待处理',
    1: '已接受',
    2: '已拒绝',
    3: '已取消'
  }
  return statusMap[status] || '未知状态'
}

// 监听标签页变化，切换到 'messages' 时开启定时刷新
watch(activeTab, (newTab) => {
  if (newTab === 'messages') {
    // 立即刷新一次
    messageListRef.value?.fetchConversations()

    // 每30秒自动刷新一次
    refreshTimer = setInterval(() => {
      messageListRef.value?.fetchConversations()
    }, 300)  // 修正为30000毫秒（30秒）
  } else {
    // 离开消息列表页，停止刷新
    if (refreshTimer) {
      clearInterval(refreshTimer)
      refreshTimer = null
    }
  }
})

// 组件销毁时清理定时器
onBeforeUnmount(() => {
  if (refreshTimer) clearInterval(refreshTimer)
})

// 添加手机验证相关状态
const showPhoneVerification = ref(false)
</script>

<style scoped>
.house-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  padding: 20px;
  max-height: 70vh;
  overflow-y: auto;
}

.house-item {
  border: 1px solid #ebeef5;
  transition: all 0.3s;
  height: 350px;
  display: flex;
  flex-direction: column;
}

.house-info {
  cursor: pointer;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.house-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.house-details {
  padding: 10px;
  flex: 1;
}

.house-details h3 {
  margin: 0 0 10px 0;
  font-size: 16px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.house-details p {
  margin: 5px 0;
  color: #606266;
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.price {
  color: #f56c6c;
  font-size: 18px;
  font-weight: bold;
}

.house-actions {
  padding: 10px;
  display: flex;
  justify-content: flex-end;
  border-top: 1px solid #ebeef5;
  background-color: #f9f9f9;
  z-index: 1;
}
</style>

<style scoped>
.layout-container {
  height: 100vh;
  background-color: #f0f2f5;
}

.header {
  background-color: #409EFF;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  box-shadow: 0 1px 4px rgba(0,21,41,.08);
}

.header-left h2 {
  color: #fff;
  margin: 0;
}

.header-right span {
  color: #fff;
}

.main-container {
  height: calc(100vh - 60px);
}

.aside {
  background-color: #304156;
  height: 100%;
}

.menu {
  border-right: none;
}

.user-info {
  padding: 20px;
  text-align: center;
  background-color: #263445;
  color: #fff;
}

.user-info h3 {
  margin: 10px 0;
  font-size: 16px;
  color: #fff;
}

.user-info .el-button {
  margin-top: 10px;
}

.main {
  padding: 20px;
  background-color: #f0f2f5;
}

.welcome-card,
.ai-service-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.welcome-content {
  padding: 20px 0;
}

.welcome-content h3 {
  color: #409EFF;
  margin-bottom: 15px;
}

.welcome-content ul {
  padding-left: 20px;
  margin-top: 10px;
}

.welcome-content li {
  line-height: 2;
  color: #666;
}

.ai-service-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}

.house-photo-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}
.house-photo-uploader .el-upload-list {
  display: flex;
  flex-direction: row;
  gap: 12px;
}
.house-photo-uploader:hover {
  border-color: #409EFF;
}

.upload-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}

.upload-text {
  position: absolute;
  bottom: 20px;
  left: 0;
  right: 0;
  text-align: center;
  color: #8c939d;
}

.preview-image {
  width: 178px;
  height: 178px;
  object-fit: cover;
}

.upload-actions {
  position: absolute;
  top: 0;
  right: 0;
  padding: 8px;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 0 0 0 4px;
}

.delete-icon {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
}

.delete-icon:hover {
  color: #f56c6c;
}

.house-form {
  margin-top: 20px;
}

.quick-actions {
  margin-top: 16px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.feedback-card {
  margin-bottom: 20px;
}

.feedback-list {
  width: 100%;
}

/* 补充 income 相关样式 */
.rental-income {
  width: 100%;
}

.overview-card,
.details-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.overview-content {
  padding: 20px 0;
}

.stat-item {
  text-align: center;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.stat-title {
  font-size: 16px;
  color: #606266;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.maintenance-detail {
  padding: 10px;
}

.result-form {
  margin-top: 20px;
}

.result-form h4 {
  margin-bottom: 10px;
  color: #409EFF;
}

</style>